<template>
  <div class="app-container">
    <!--搜索条件-->
    <div class="filter-container">
      <el-form :model="listQuery" :inline="true">
        <el-form-item>
          <el-input v-model="listQuery.dataDictName" :placeholder="'请输入'+name+'名称'" class="filter-item" @keyup.enter.native="handleFilter" />
        </el-form-item>
        <el-form-item>
          <el-button plain type="primary" icon="el-icon-search" @click="handleFilter">搜索</el-button>
          <el-button plain icon="el-icon-refresh" @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div v-if="currentDataDict.dataDictName" class="filter-container" style="padding-bottom:10px">
      当前选择：
      <span class="color-primary">
        {{ currentDataDict.dataDictName+'('+currentDataDict.dataDictCode+') '+(currentDataDict.isNationalStandard==1?'标准 ':' ')+(currentDataDict.remark?currentDataDict.remark:'') }}
      </span>
      <copy-text :content="currentDataDict.dataDictCode" :show="false" style="padding-top: 11px;" />
    </div>
    <!--列表-->
    <div class="table-container flex-main">
      <div class="table-container-header">
        <table-toolbar @create="handleCreateType" @refresh="handleFilter" @remove="removeRecordType" />
      </div>
      <el-form
        ref="typeForm"
        class="common-table-form"
        style="height: 100%;"
        :rules="dataDictItemRules"
        :model="dataDictItemRecord"
        label-position="right"
        label-width="0">
        <el-table
          ref="multipleTable"
          :data="list"
          header-cell-class-name="table-header"
          fit
          highlight-current-row
          stripe
          style="height: 100%;"
          height="100%"
          @selection-change="handleSelectionChange"
          @row-click="handleRowClick"
          @sort-change="sortChange">
          <el-table-column type="selection" width="40" />
          <el-table-column align="center" label="#" width="60">
            <template slot-scope="scope">{{ scope.$index+1 }}</template>
          </el-table-column>
          <el-table-column prop="dataDictCode" sortable width="150" align="left" :show-overflow-tooltip="true">
            <template #header>
              <span class="color-danger">*</span>&nbsp;代码
            </template>
            <template slot-scope="scope">
              <el-form-item v-if="scope.row.isModified===true" prop="dataDictCode">
                <el-input v-model="dataDictItemRecord.dataDictCode" :disabled="scope.row.formOption==='update'" maxlength="40" :placeholder="'请输入'+name+'代码'" show-word-limit />
                <template slot="error" slot-scope="itemScope">
                  <el-tooltip :content="itemScope.error" placement="top">
                    <i v-if="itemScope.error" class="el-icon-warning-outline item-error" />
                  </el-tooltip>
                </template>
              </el-form-item>
              <template v-else>
                {{ scope.row.dataDictCode }}
              </template>
            </template>
          </el-table-column>
          <el-table-column prop="dataDictName" min-width="150" sortable align="left">
            <template #header>
              <span class="color-danger">*</span>&nbsp;{{ name }}
            </template>
            <template slot-scope="scope">
              <div class="flex-row">
                <el-form-item v-if="scope.row.isModified===true" prop="dataDictName">
                  <el-color-picker v-model="dataDictItemRecord.colorValue" style="margin-right;:5px" />
                  <el-input v-model="dataDictItemRecord.dataDictName" maxlength="45" :placeholder="'请输入'+name+'代码'" show-word-limit />
                  <template slot="error" slot-scope="itemScope">
                    <el-tooltip :content="itemScope.error" placement="top">
                      <i v-if="itemScope.error" class="el-icon-warning-outline item-error" />
                    </el-tooltip>
                  </template>
                </el-form-item>
                <template v-else>
                  <dot v-if="scope.row.colorValue" :color="scope.row.colorValue" />
                  <div> {{ scope.row.dataDictName }}</div>
                </template>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="isBuiltIn" label="标签" width="130">
            <template slot-scope="scope">
              <el-form-item v-if="scope.row.isModified===true" prop="isNationalStandard">
                <el-tooltip content="是否国家标准" placement="top">
                  <i class="el-icon-warning-outline item-tip" />
                </el-tooltip>
                <el-switch
                  v-model="dataDictItemRecord.isNationalStandard"
                  :active-value="1"
                  :inactive-value="0" />
              </el-form-item>
              <template v-else>
                <el-link v-if="scope.row.isBuiltIn==1" class="color-primary " :underline="false">内置</el-link>
                <el-link v-if="scope.row.isBuiltIn==0" class="color-success " :underline="false">平台</el-link>
                <el-link v-if="scope.row.isNationalStandard==1" class="color-primary " :underline="false">标准</el-link>
                <el-link v-if="scope.row.isNationalStandard==0" class="color-success " :underline="false">非标准</el-link>
              </template>
            </template>
          </el-table-column>

          <el-table-column label="排序" prop="sortValue" sortable width="130" align="center" :show-overflow-tooltip="true">
            <template #header>
              <span class="color-danger">*</span>&nbsp;排序
            </template>
            <template slot-scope="scope">
              <el-form-item v-if="scope.row.isModified===true" prop="sortValue">
                <el-input-number v-model="dataDictItemRecord.sortValue" placeholder="请输入排序" show-word-limit :max="99" style="width:100%" />
                <template slot="error" slot-scope="itemScope">
                  <el-tooltip :content="itemScope.error" placement="top">
                    <i v-if="itemScope.error" class="el-icon-warning-outline item-error" />
                  </el-tooltip>
                </template>
              </el-form-item>
              <template v-else>
                {{ scope.row.sortValue }}
              </template>
            </template>
          </el-table-column>

          <el-table-column prop="gmtModified" sortable label="修改时间" width="160">
            <template slot-scope="scope">{{ scope.row.gmtModified | formatDate }}</template>
          </el-table-column>
          <el-table-column label="操作" align="center" fixed="right" width="90">
            <template slot-scope="scope">
              <template v-if="scope.row.isModified===true">
                <button-option icon="el-icon-check" skin="primary" title="保存" @click="scope.row.formOption==='update'?updateTypeData():createTypeData()" />
                <button-option icon="el-icon-close" skin="danger" title="取消" @click="handleCancel(scope.row)" />
              </template>
              <template v-else>
                <button-option icon="el-icon-edit" skin="primary" title="编辑" @click="handleUpdateType(scope.row)" />
                <button-option icon="el-icon-delete" skin="danger" title="删除" @click="handleRemoveSingleType(scope.row)" />
              </template>

            </template>
          </el-table-column>
        </el-table>
      </el-form>
    </div>
    <div class="pagination_handler">
      <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="fetchData" />
    </div>
    <!--新增/编辑字典项侧边栏-->
    <side-box :show="sideBox.typeShow" :title="sideBox.title" @close="sideBox.typeShow = !sideBox.typeShow">
      <template slot="body">
        <el-form
          ref="typeForm"
          :rules="dataDictItemRules"
          :model="dataDictItemRecord"
          label-position="right"
          label-width="120px">
          <el-form-item label="所属字典组:">
            <el-input v-model="currentDataDict.dataDictName" :disabled="true" />
          </el-form-item>
          <el-form-item label="颜色值:" prop="colorValue">
            <el-color-picker v-model="dataDictItemRecord.colorValue" style="margin-top:5px" />
          </el-form-item>
          <el-form-item label="排序:" prop="sortValue">
            <el-input-number v-model="dataDictItemRecord.sortValue" placeholder="请输入排序" show-word-limit :max="99" style="width:100%" />
          </el-form-item>
        </el-form>
      </template>
      <template slot="foot">
        <el-button plain type="primary" @click="sideBox.status==='create'?createTypeData():updateTypeData()">保存</el-button>
      </template>
    </side-box>
  </div>
</template>

<script>
export default {
  props: {
    code: {
      type: String,
      default: ''
    },
    name: {
      type: String,
      default: '字典项'
    }
  },
  data() {
    return {
      sideBox: {},
      list: null,
      total: 0,
      listQuery: {
        page: 1,
        limit: this.common.PAGE_LIMIT_DEFAULT,
        dataDictName: '',
        pid: '-1',
        sort: '-sortValue'
      },
      currentDataDict: {},
      // 固定写法
      multipleSelectionRecords: [],
      dataDictItemRecord: {},
      dataDictItemRules: {
        dataDictName: [
          { required: true, message: '请输入' + this.name + '名称', trigger: 'blur' },
          { validator: this.$validate.checkInput, trigger: 'blur' }
        ],
        dataDictCode: [
          { required: true, message: '请输入' + this.name + '代码', trigger: 'blur' },
          { validator: this.$validate.validateEngOrNum, trigger: 'blur' }
        ],
        sortValue: [
          { required: true, message: '请输入排序', trigger: 'blur' },
          { validator: this.$validate.validateNumber, trigger: 'blur' }
        ]
      }
    }
  },
  watch: {
    code: function() {
      this.fetchDataDict()
    }
  },
  created() {
    this.fetchDataDict()
  },
  methods: {
    fetchDataDict() {
      if (this.code) {
        this.$store.dispatch('getDataDictByCode', this.code).then((res) => {
          this.currentDataDict = res || {}
          if (res) {
            this.fetchData()
          }
        })
      } else {
        this.currentDataDict = {}
        this.list = []
      }
    },
    // 固定写法开始
    /**
     * 表格全选/反选
     */
    handleSelectionChange(val) {
      this.multipleSelectionRecords = val
    },
    /**
     * 表格排序
     */
    sortChange(data) {
      const { prop, order } = data
      if (prop) {
        if (order === 'ascending') {
          this.listQuery.sort = '+' + prop
        } else {
          this.listQuery.sort = '-' + prop
        }
      } else {
        this.listQuery.sort = '-sortValue'
      }
      this.handleFilter()
    },
    /**
     * 表格行单击
     */
    handleRowClick(row) {
      this.$refs.multipleTable.toggleRowSelection(row)
    },
    // 固定写法结束
    async fetchData() {
      this.listQuery = {
        ...this.listQuery,
        pid: this.currentDataDict.id
      }
      const response = await this.$store.dispatch('dataDictItemPage', this.listQuery)
      this.list = response.records
      this.total = response.total
    },
    /**
     * 搜索
     */
    handleFilter() {
      this.listQuery = {
        ...this.listQuery,
        page: 1
      }
      this.fetchData()
    },
    /**
     * 重置
     */
    handleReset() {
      this.listQuery = {
        ...this.listQuery,
        page: 1,
        limit: this.common.PAGE_LIMIT_DEFAULT,
        dataDictName: undefined,
        sort: '-sortValue'
      }
      this.$refs.multipleTable.clearSort()
      this.$refs.multipleTable.clearFilter()
      this.fetchData()
    },
    handleCancel(row) {
      if (row.formOption === 'update') {
        this.$set(row, 'isModified', false)
      } else {
        this.list = this.list.filter(item => {
          return item.id !== row.id
        })
      }
    },
    // 固定写法结束
    handleCreateType() {
      if (!this.currentDataDict.id) {
        this.$modal.msgWarning('缺少字典项')
        return
      }
      if (this.list.filter(item => { return item.isModified === true }).length > 0) {
        this.$modal.msgWarning('请先完成未提交的记录！')
        return
      }
      this.dataDictItemRecord = {
        isNationalStandard: this.currentDataDict.isNationalStandard,
        sortValue: this.list == null ? 99 : 99 - this.list.length
      }
      this.list.unshift({
        ...this.dataDictItemRecord,
        isModified: true,
        formOption: 'create',
        id: this.T.uuid()
      })
      this.$nextTick(() => {
        this.$refs['typeForm'].clearValidate()
      })
    },
    createTypeData() {
      this.$refs['typeForm'].validate(valid => {
        if (valid) {
          this.dataDictItemRecord.pid = this.listQuery.pid
          this.$store.dispatch('dataDictItemSave', this.dataDictItemRecord).then(response => {
            this.$modal.msgSuccess('创建成功')
            this.handleReset()
          }).catch(() => {
          })
        }
      })
    },
    handleUpdateType(row) {
      if (this.list.filter(item => { return item.isModified === true }).length > 0) {
        this.$modal.msgWarning('请先完成未提交的记录！')
        return
      }
      this.list.forEach((item, index) => {
        item.isModified = false
        this.$set(this.list, index, item)
      })
      this.dataDictItemRecord = Object.assign({}, row)
      this.$set(row, 'isModified', true)
      this.$set(row, 'formOption', 'update')
    },
    updateTypeData() {
      this.$refs['typeForm'].validate(valid => {
        if (valid) {
          const tempData = Object.assign({}, this.dataDictItemRecord)
          this.$store.dispatch('dataDictItemUpdate', tempData).then(response => {
            this.$modal.msgSuccess('修改成功')
            this.handleFilter()
          }).catch(() => {
          })
        }
      })
    },
    // 删除数据项
    handleRemoveSingleType(row) {
      this.multipleSelectionRecords = []
      this.multipleSelectionRecords.push(row)
      this.$refs.multipleTable.clearSelection()
      this.$refs.multipleTable.toggleRowSelection(row, true)
      this.removeRecordType()
    },
    removeRecordType(nodeId) {
      if (nodeId !== undefined) {
        this.multipleSelectionRecords.push({ id: nodeId })
      }
      if (this.multipleSelectionRecords.length > 0) {
        const ids = []
        this.multipleSelectionRecords.forEach(function(v, i) {
          if (v.isBuiltIn === 0) {
            ids.push(v.id)
          }
        })
        if (ids.length === 0) {
          this.$modal.msgWarning('你选择的数据都是内置数据,无权删除')
          return
        }
        this.$confirm('此操作将永久删除记录, 是否继续?', '删除提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$store.dispatch('dataDictRemove', ids).then(response => {
            this.handleReset()
            this.$modal.msgSuccess('删除成功')
          }).catch(() => {})
        }).catch(() => { })
      } else {
        this.$modal.msgWarning('请选择要删除的记录')
      }
    }
  }
}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>

</style>
